import re

from rest_framework import serializers


class UserLoginForms(serializers.Serializer):
    """
        用户登录表单
    """
    username = serializers.CharField(max_length=16, allow_blank=False, allow_null=False, error_messages={
        'blank': '用户名不能为空',
        'null': '用户名不能为null',
        'max_length': '用户名长度不能超过16个字符',
    })
    password = serializers.CharField(max_length=32, allow_blank=False, allow_null=False, error_messages={
        'blank': '密码不能为空',
        'null': '密码不能为null',
        'max_length': '密码长度不能超过32个字符',
    })

    def validate_username(self, value) -> str:
        """
            账号验证
        """
        username: str = value
        if username.__contains__('@'):
            # ---- 邮箱格式验证 ----
            if not is_valid_email(username):
                raise serializers.ValidationError('邮箱格式不正确')
        else:
            # ---- 账号格式验证 ----
            if len(username) < 6:
                raise serializers.ValidationError('账号长度不能少于6位')
        return username

    def validate_password(self, value) -> str:
        """
            密码验证
        """
        password: str = value
        if len(password) < 6:
            raise serializers.ValidationError('密码长度不能少于6位')
        return password

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass


def is_valid_email(email) -> bool:
    """
    验证邮箱格式
    """
    email_pattern = re.compile(r'^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$')
    return bool(email_pattern.match(email))


def is_valid_phone(phone) -> bool:
    """
    验证手机号格式
    """
    phone_pattern = re.compile(r'^1[3456789]\d{9}$')
    match = phone_pattern.match(phone)
    return bool(match)
